package org.lucky.admin.excption;

import org.lucky_common.exception.BusinessException;
import org.lucky_common.util.AjaxResult;
import org.lucky_common.util.ResponseCode;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author RTX 9090
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessException(BusinessException e){
        ResponseCode responseCode = e.getResponseCode();
        System.out.println(e.getMessage());
        if (responseCode==null){
            return AjaxResult.error(e.getMessage());
        }else {
            return AjaxResult.error(e.getMessage(), responseCode.getCode());
        }
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult jsr303Exception(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        List<ObjectError> allErrors = result.getAllErrors();
        StringBuilder sb = new StringBuilder();
        for(ObjectError error : allErrors){
            sb.append(error.getDefaultMessage()).append(",");
        }
        return AjaxResult.error(sb.toString(),ResponseCode.RESPONSE_CODE_400.getCode());
    }

}